package pl.edu.romanow.snippet

import xml.NodeSeq
import pl.edu.romanow.model.Database
import net.liftweb.common.Full
import net.liftweb.util.Helpers._
import scala.collection.JavaConversions._
import pl.edu.romanow.model.GraphHelper._
import Database.G
import net.liftweb.http.{SHtml, Templates}
import pl.edu.romanow.util.HTMLUtil
import net.liftweb.http.js.{JsCmds, JsCmd}
import net.liftweb.http.js.jquery.JqJsCmds
import com.tinkerpop.blueprints.pgm.Vertex

/**
 * Created with IntelliJ IDEA.
 * User: jar
 * Date: 26.05.12
 * Time: 22:38
 * To change this template use File | Settings | File Templates.
 */

object RightMenu {

  def showUser(id: String, source: String = "Facebook"): JsCmd = JqJsCmds.Show("right_menu_content") &
    JsCmds.SetHtml("right_menu_content", bindUserInfo(id, source))


  def bindUserInfo(id: String, source: String = "Facebook"): NodeSeq = {

    val mgr = Database.appCon
    val user = mgr.getVertex(id).openOr(return <span>No such User id:
      {id}
    </span>)
    var selected = ""

    (
      "#object_id *" #> (user \ (source + "Id")) &
        "#object_name *" #> (user \ "name") &
        "#start_with [onclick]" #> JsCmds.Run("setBeg(%s);".format((user \ (source + "Id")))).toJsCmd &
        "#field" #> user.getPropertyKeys.filter(k => k != source + "Id" || k != "name").map {
          key =>
            "#label *" #> key &
              "#value *" #> (user \ key)
        } &
        "#connections" #> SHtml.idMemoize {
          outer =>
            "#connection" #>
              G(user).bothE().label().toList.toSet.map {
                label: String =>
                  "#connection_label *" #> label &
                    "#showConnection [onclick]" #> HTMLUtil.ajaxCall {
                      selected = label
                      outer.setHtml()
                    } &
                    (if (label == selected)
                      "#connectionItem" #> G(user).both(label).toList.toSet.map {
                        item: Vertex =>
                          "#connected_user [onclick]" #> showUser(item.getId.toString) &
                            "#connected_user *" #>
                              ((item \? "name") match {
                                case Full(name) => name
                                case _ => item.getId.toString
                              })
                      }
                    else
                      "#connectionList" #> NodeSeq.Empty)
              }
        }

      )(Templates("rightPanel" :: "objectInfo" :: Nil).openTheBox)


  }


}
